package com.ocom.oauth.auth.aiotweb;

import com.ocom.oauth.auth.CustomAbstractTokenGranter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

/**
 *
 *  说明：
 *    验证码
 *    定义验证码具体逻辑
 */
public class AiotWebTokenGranter extends CustomAbstractTokenGranter {

    private static final String AIOT_AUTH = "aiot_auth";

    private AiotUserDetailService aiotUserDetailService;

    public AiotWebTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, AiotUserDetailService aiotUserDetailService) {
        super(tokenServices, clientDetailsService, requestFactory, AIOT_AUTH);
        this.aiotUserDetailService = aiotUserDetailService;
    }

    @Override
    protected UserDetails getUserDetails(Map<String, String> parameters) {
        String account = parameters.get("account");
        String verify = parameters.get("verify");
        String password = parameters.get("password");
        if (account==null) {
            throw new InvalidGrantException("账号传参错误或者为空值，请输入正确的账号信息");
        }
        if (password==null) {
            throw new InvalidGrantException("密码传参错误或者为空值，请输入正确的密码信息");
        }
        if (verify==null) {
            throw new InvalidGrantException("验证码传参错误或者为空值，请输入正确的验证码信息");
        }
        return aiotUserDetailService.loadByNameAndCode(account,password,verify);
    }
}
